/**
 * 
 */
package org.youisoft.summer.evaluator.function.clustering;

import java.util.List;

import org.youisoft.summer.evaluator.InvokeException;
import org.youisoft.summer.evaluator.context.CalContext;
import org.youisoft.summer.evaluator.function.Function;
import org.youisoft.summer.evaluator.operator.Operator;
import org.youisoft.summer.evaluator.operator.base.ListOperator;
import org.youisoft.summer.evaluator.operator.base.NumberOperator;

/**
 * @author zijiang.jl
 *
 */
public class KTmesFunction extends AbstractKSeriesFunction{
	

	@Override
	protected int defaultKNumber() {
		return 3;
	}

	@Override
	protected void adjustCenter(double[] center,List<Number> points, int[] centerIndex) {
		for(int j=0;j<center.length;j++){
			double temp=0;
			int cnt=0;
			for(int i=0;i<centerIndex.length;i++){
				if(j==centerIndex[i]){
					temp+=points.get(i).doubleValue();
					cnt++;
				}
			}
			
			if(cnt!=0) center[j]=temp/cnt;
		}
	}

	@Override
	protected <C, R, P> List<Operator<?>> outlierClustering(
			CalContext<C, R, P> context, double[] center, List<Number> points,
			int[] centerIndex,double factor) throws InvokeException{
		NumberOperator no=new NumberOperator(center.length);
		ListOperator<Operator<?>> lo=new ListOperator<Operator<?>>();
		for(int i=0;i<center.length;i++){
			lo.addOperator(new NumberOperator(center[i]));
		}
		
		Function f=this.findFunction("kmedoids");
		
		@SuppressWarnings("unchecked")
		ListOperator<Operator<?>> res=ListOperator.class.cast(f.invoke(context, lo,no));
		
		java.util.List<Operator<?>> normalPoints=new java.util.ArrayList<Operator<?>>();
		for(Operator<?> op:res.value()){
			for(int i=0;i<centerIndex.length;i++){
				if(center[centerIndex[i]]==Number.class.cast(op.value()).doubleValue()){
					normalPoints.add(new NumberOperator(points.get(i)));
				}
			}
		}
		return normalPoints;
		
	}

}
